package com.woniu.inlet.timer;

import com.woniu.adapter.MessageRepositoryAdapter;
import com.woniu.service.domain.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class SendingMessageTask {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MessageRepositoryAdapter messageRepositoryAdapter;

    @Scheduled(fixedRate = 5000)
    public void sendMessage() {
        log.debug("定时任务起来干活...");
        // 查询条件是：（状态为未发送且发送次数非 0）的消息，都需要发送。
        List<Message> messageList = messageRepositoryAdapter.selectMessageForSend();
        log.debug("查询符合条件的待发送消息，共[{}]条", messageList.size());

        if (messageList.size() == 0)
            return;

        // 循环发送所有待发送消息，并将它们的发送次数减一。
        for (Message message : messageList) {
            CorrelationData data = new CorrelationData(message.getId().toString());
            log.debug("发送消息[{}]", data.getId());
            // 可靠消息服务投递的消息的真实内容="消息的ID:消息的原始内容"
            String realContent = message.getId() + "!" + message.getMessageContent();
            rabbitTemplate.convertAndSend(
                    message.getExchange(),
                    message.getRoutingKey(),
                    realContent,
                    data
            );

            message.setRetryCount(message.getRetryCount() - 1);
            log.debug("消息[{}]发送次数减1，应减为[{}]", data.getId(), message.getRetryCount());
            messageRepositoryAdapter.updateMessageRetryCount(message);
        }
    }
}
